package com.freework.tree;

import java.util.ArrayList;
import java.util.Arrays;
import java.util.HashMap;
import java.util.Iterator;
import java.util.LinkedList;
import java.util.List;
import java.util.Map;
import java.util.Set;
import java.util.Stack;

import org.springframework.stereotype.Service;
@Service
public class TreeStructureService implements TreeStructureServiceI{
	public List toBornTree(List list, Integer rootid) {
		List<TreeDatas> rootList = new LinkedList<TreeDatas>();
		TreeDatas treedata = null;
		HashMap<Integer,List<TreeDatas>> branchsMap = new HashMap<Integer,List<TreeDatas>>(60, 0.5f);
		for (Iterator iterator = list.iterator(); iterator.hasNext();) {
			 treedata = (TreeDatas) iterator.next();
			if (treedata != null
					&& (treedata.getPid() == null
							 || treedata.getPid().equals(rootid))) {
				rootList.add(treedata);
			} else {
				List<TreeDatas> branchsList =  branchsMap.get(treedata.getPid());
				if (branchsList == null) {
					branchsList = new LinkedList<TreeDatas>();
					branchsMap.put(treedata.getPid(), branchsList);
				}
				branchsList.add(treedata);
			}
		}
		for (Iterator<TreeDatas> iterator = rootList.iterator(); iterator.hasNext();) {
			TreeDatas root = (TreeDatas) iterator.next();
			root.setChildren( branchsMap.get(root.getId()));
			root.setLeaf(root.getChildren()==null);
			branchsMap.remove(root.getId());
			
		}
		this.toBornTree(list, branchsMap);
		return rootList;

	}

	public void toBornTree(List list, Map branchs) {
		TreeDatas treedata = null;

		List childerens = null;

		for (int i = 0; i <list.size(); i++) {
			treedata = (TreeDatas) list.get(i);
			childerens = (List) branchs.get(treedata.getId());
			if (childerens != null) {
				treedata.setLeaf(false);
				treedata.setChildren(childerens);
			}

		}

	}
	// public void toBornTree(List list, TreeDatas nord,int size) {
	// TreeDatas treedata=null;
	// for (int i = 0; i <size; i++) {
	// treedata=(TreeDatas) list.get(i);
	// if ( nord.getId().equals(treedata.getPid())) {
	// nord.setLeaf(false);
	// List childrenList = nord.getChildren();
	// if (childrenList == null) {
	// childrenList = new ArrayList();
	//
	// }
	// childrenList.add(treedata);
	// nord.setChildren(childrenList);
	// toBornTree(list,treedata,size);
	// }
	// }
	//
	// }
}
